package com.nx.platform.es.biz.esspider.source;

import com.google.common.base.Preconditions;
import com.google.common.primitives.Longs;
import com.google.common.util.concurrent.AbstractIdleService;
import com.nx.platform.es.biz.esspider.deliver.Deliverer;
import com.nx.platform.es.biz.esspider.entity.Message;
import com.nx.platform.es.common.utils.MoreSplitters;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @author
 * @date 2018/01/25
 */
public class InvokeSourceService extends AbstractIdleService implements SourceService {

    private static final Logger LOGGER = LogManager.getLogger(InvokeSourceService.class);

    private final Deliverer deliverer;

    public InvokeSourceService(Deliverer deliverer) {
        this.deliverer = deliverer;
    }

    @Override
    protected void startUp() throws Exception {}

    @Override
    protected void shutDown() throws Exception {}

    public void notify(String logStr, String message) {
        Preconditions.checkState(isRunning());
        deliverer.deliver(parse(logStr, message));
    }

    private Message parse(String logStr, String message) {
        String[] arr = MoreSplitters.COMMA.split(message);
        if (arr.length < 2) {
            LOGGER.warn("{} message ignored, {}", logStr, message);
            return null;
        }
        String type = arr[0].trim();
        Long id = Longs.tryParse(arr[1].trim());
        if (id == null) {
            LOGGER.warn("{} message ignored, {}", logStr, message);
            return null;
        }
        String line = String.format("logStr:%s, message:%s", logStr, message);
        return new Message(InvokeSourceService.class, type, id, null, line);
    }

}
